package cn.com.cetccst.appstore.ui.fragment.viewmodel;

import android.content.Context;
import android.widget.Toast;

import androidx.lifecycle.LiveData;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.database.model.CategoryModel;
import cn.com.cetccst.appstore.log.AppStoreLogger;
import cn.com.cetccst.appstore.network.AppStoreHttpRequester;
import cn.com.cetccst.appstore.network.response.CategoryListResponse;
import cn.com.cetccst.network.BaseCallback;
import cn.com.cetccst.tools.network.Connectivity;
import cn.com.cetccst.tools.ui.ThreadSafeToast;


public class CategoryListViewModel extends BaseViewModel {

    //分类没有搜索功能。这里直接从数据库驱动了
    public final LiveData<List<CategoryModel>> list = AppStoreRepository.getInstance().loadAllCategory();

    public void requestCategoryList(Context context) {

        //网络请求
        Map<String, String> queryMap = new HashMap<>();
        if (Connectivity.isNetworkConnected(context)) {
            if (AppStoreHttpRequester.getInstance() != null) {
                queryMap.put("limit", "1000");
                queryMap.put("orderby", "update_time");//orderby=update_time&ascending=false
                queryMap.put("ascending", "false");
                queryMap.put("with_store", "false");
                queryMap.put("offset", 0 + "");
            }
        } else {
            ThreadSafeToast.show(R.string.store_error_network_down, Toast.LENGTH_LONG);
            //防止下来刷新
            refreshing.setValue(false);
            return;
        }

        refreshing.setValue(true);
        AppStoreHttpRequester.getInstance().requestCategoryList(queryMap, new BaseCallback<>() {
            @Override
            public void onResponse(CategoryListResponse data) {
                refreshing.setValue(false);
                if (data != null) {
                    if (data.getErrCode() != 0) {
                        ThreadSafeToast.show(context.getString(R.string.store_http_response, data.getErrMessage()), Toast.LENGTH_SHORT);
                    } else {
                        AppStoreRepository.getInstance().saveCategoryModel(data.getCategoryList());
                    }

                } else {
                    AppStoreLogger.info("getCategoryNameByCategoryId context or data is null");
                    ThreadSafeToast.show(R.string.store_network_failed, Toast.LENGTH_LONG);
                }
            }
        });
    }
}
